package com.github;

import com.github.util.DataBaseInitUtil;
import com.github.util.HttpUtil;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.IOException;
import java.util.List;

import static com.github.drinkjava2.jsqlbox.JSQLBOX.nQueryForIntValue;

public class UiApplication {
    public static JTextArea log=null;
    public static boolean iszjcj=true;
    public static boolean isAutoDo=false;
    public static void main(String[] args) {
        DataBaseInitUtil.init();

        // 创建 JFrame 实例
        JFrame frame = new JFrame("MavenJar下载工具");
        // Setting the width and height of frame
        frame.setSize(830, 550);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        /* 创建面板，这个类似于 HTML 的 div 标签
         * 我们可以创建多个面板并在 JFrame 中指定位置
         * 面板中我们可以添加文本字段，按钮及其他组件。
         */
        JPanel leftpanel = new JPanel();
        JPanel botpanel=new JPanel();
        botpanel.setBorder(BorderFactory.createTitledBorder("操作日志"));
        botpanel.setBounds(10,100,800,400);
        JTextArea jta=new JTextArea("",23,64);
      //  jta.setBounds(1,1,750,460);
        jta.setLineWrap(true);    //设置文本域中的文本为自动换行
        jta.setForeground(Color.BLACK);    //设置组件的背景色
       // jta.setFont(new Font("楷体",Font.BOLD,16));    //修改字体样式
       // jta.setBackground(Color.YELLOW);    //设置按钮背景色
        JScrollPane jsp=new JScrollPane(jta);    //将文本域放入滚动窗口
        //Dimension size=jta.getPreferredSize();    //获得文本域的首选大小
       // jsp.setBounds(110,90,size.width,size.height);
        botpanel.add(jsp);    //将JScrollPane添加到JPanel容器中
        log=jta;
        JLabel labelpath=new JLabel("Maven仓库下载目录:");
        labelpath.setBounds(10,10,140,25);
        final JTextField txtPath=new JTextField(10);
        txtPath.setText("/Users/wishes/Downloads");
        txtPath.setBounds(150,10,200,25);
        JLabel labelis=new JLabel("是否逐级创建目录:");
        labelis.setBounds(360,10,110,25);
        ButtonGroup group=new ButtonGroup();
        JRadioButton rb1=new JRadioButton("是");    //创建JRadioButton对象
        rb1.setSelected(true);
        rb1.setBounds(470,10,50,25);
        JRadioButton rb2=new JRadioButton("否");    //创建JRadioButton对象
        rb2.setBounds(520,10,50,25);
        group.add(rb1);
        group.add(rb2);
        rb1.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                switch (e.getStateChange()){
                    case ItemEvent.SELECTED:
                        iszjcj=true;
                        break;
                }
            }
        });
        rb2.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                switch (e.getStateChange()){
                    case ItemEvent.SELECTED:
                        iszjcj=false;
                        break;
                }
            }
        });
        leftpanel.add(rb1);
        leftpanel.add(labelis);
        leftpanel.add(rb2);
        JCheckBox isAutoDownload = new JCheckBox("是否强制下载");
        isAutoDownload.setBounds(580,10,120,25);
        isAutoDownload.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent e) {
                JCheckBox checkBox = (JCheckBox) e.getSource();
                if(checkBox.isSelected()){
                    isAutoDo=true;
                }else
                {
                    isAutoDo=false;
                }
            }
        });
        leftpanel.add(isAutoDownload);
        // 添加面板
        JLabel jl=new JLabel("名称:");
        jl.setBounds(10,50,40,25);
        final JTextField txtSearch=new JTextField(10);
        txtSearch.setBounds(50,50,200,25);
        JButton btnsearch=new JButton("搜索");
        btnsearch.setBounds(250,50,50,25);
        JLabel lsrs=new JLabel("搜索结果:");
        lsrs.setBounds(300,50,60,25);
        final JComboBox cmbRs=new JComboBox();
        cmbRs.setBounds(360,50,200,25);
        JLabel lsrsV=new JLabel("版本:");
        lsrsV.setBounds(560,50,40,25);
        final JComboBox cmbRsv=new JComboBox();
        cmbRsv.setBounds(600,50,100,25);
        JButton btndownload=new JButton("下载");
        btndownload.setBounds(710,50,50,25);
        btnsearch.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                cmbRs.removeAllItems();
                log.append("正在搜索"+txtSearch.getText()+"....\r\n");
                    new Thread(){
                        public void run(){
                            try{
                                List<MavenBean> rs = HttpUtil.getSearchList(txtSearch.getText());
                                if(rs==null)return;
                                log.append("搜索结束,共"+rs.size()+"条相关记录\r\n");
                                UiApplication.log.setSelectionStart(UiApplication.log.getText().length());
                                for (MavenBean b:rs
                                ) {
                                    cmbRs.addItem(b);
                                }
                            } catch (IOException e1) {
                                e1.printStackTrace();
                            }
                        }
                    }.start();
            }
        });
        btndownload.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                new Thread(){
                    public void run(){
                        MavenBean choose= (MavenBean) cmbRs.getSelectedItem();
                        MavenVersion version= (MavenVersion) cmbRsv.getSelectedItem();
                        int i = nQueryForIntValue("select count(1) from downloadHistory where artifactId=? and groupId=? and version=? and state=2",
                                choose.getArtifactId(), choose.getGroupId(), version.getRelease());
                        if(i>0&&!isAutoDo){
                            log.append("本地已存在=》"+choose.getGroupId()+">"+choose.getArtifactId()+">"+version.getRelease()+"\r\n");
                            return;
                        }
                        String[] s = choose.getGroupId().split("\\.");
                        String[] dir=new String[s.length+2];
                        for (int j = 0; j < s.length; j++) {
                            dir[j]=s[j];
                        }
                        dir[dir.length-2]=choose.getArtifactId();
                        dir[dir.length-1]=version.getRelease();
                        try {
                            log.append("开始下载"+choose.getGroupId()+">"+choose.getArtifactId()+">"+version.getRelease()+"\r\n");
                           HttpUtil.downloadByVersion(version.getUrl(),dir,txtPath.getText(),choose.getArtifactId(),choose.getGroupId(),version.getRelease());
                            UiApplication.log.setSelectionStart(UiApplication.log.getText().length());
                            log.append(choose.getGroupId()+">"+choose.getArtifactId()+">"+version.getRelease()+"下载结束\r\n");
                            UiApplication.log.setSelectionStart(UiApplication.log.getText().length());
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    }
                }.start();


            }
        });
        cmbRs.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                switch (e.getStateChange()){
                    case ItemEvent.SELECTED:
                        cmbRsv.removeAllItems();
                            new Thread(){
                                public void run(){
                                    try{
                                        MavenBean mb= (MavenBean) cmbRs.getSelectedItem();
                                        log.append("开始加载"+mb.getName()+"版本列表....\r\n");
                                        List<MavenVersion> rs = HttpUtil.getVersions(mb.getUrl());
                                        for (MavenVersion v:rs
                                        ) {
                                            cmbRsv.addItem(v);
                                        }
                                        log.append("共发现版本:"+rs.size()+"条\r\n");
                                        log.append("版本列表加载结束....\r\n");
                                        UiApplication.log.setSelectionStart(UiApplication.log.getText().length());
                                    } catch (IOException e1) {
                                        e1.printStackTrace();
                                    }
                                }
                            }.start();
                        break;
                }
            }
        });
        leftpanel.setBorder(BorderFactory.createRaisedBevelBorder());
       // leftpanel.setPreferredSize(new Dimension(300, 300));
        leftpanel.setLayout(null);
        leftpanel.add(jl);
        leftpanel.add(txtSearch);
        leftpanel.add(btnsearch);
        leftpanel.add(cmbRs);
        leftpanel.add(lsrs);
        leftpanel.add(lsrsV);
        leftpanel.add(cmbRsv);
        leftpanel.add(btndownload);
        leftpanel.add(labelpath);
        leftpanel.add(txtPath);
        leftpanel.add(botpanel);
        frame.add(leftpanel,BorderLayout.CENTER);

        /*
         * 调用用户定义的方法并添加组件到面板
         */


        int windowWidth = frame.getWidth(); //获得窗口宽
        int windowHeight = frame.getHeight(); //获得窗口高
        Toolkit kit = Toolkit.getDefaultToolkit(); //定义工具包
        Dimension screenSize = kit.getScreenSize(); //获取屏幕的尺寸
        int screenWidth = screenSize.width; //获取屏幕的宽
        int screenHeight = screenSize.height; //获取屏幕的高
        frame.setLocation(screenWidth/2-windowWidth/2, screenHeight/2-windowHeight/2);//设置窗口居中显示
        // 设置界面可见
        frame.setVisible(true);
    }


}
